package com.atguigu.gmall.cart.service.impl;

import com.atguigu.gmall.cart.mapper.CartInfoMapper;
import com.atguigu.gmall.cart.service.CartInfoAsyncService;
import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartInfoServiceImpl implements CartInfoService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CartInfoMapper cartInfoMapper;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private CartInfoAsyncService cartInfoAsyncService;

    @Override
    public void addToCart(Long skuId, Integer skuNum, String userId) {
        System.out.println("addToCart:userId:" + userId);//32长度串
        //查询缓存key为 user:3:cart
        String cacheKey = RedisConst.USER_KEY_PREFIX +
                userId + RedisConst.USER_CART_KEY_SUFFIX;
        //1、查询商品在购物车中是否存在
        CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cacheKey,skuId.toString());
        if (null != cartInfo){
            //2、存在
            cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
            //设置选中
            cartInfo.setIsChecked(1);
            //DB 更新
            //优化：使用多线程
//            cartInfoMapper.updateById(cartInfo);
            cartInfoAsyncService.updateAsyncById(cartInfo);
        }else {
            //TODO 缓存中没有cartInfo不代表DB里没有，可能会导致重复添加
            //3、不存在,则新建一个该商品的购物车对象
            cartInfo = new CartInfo();
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(skuId);
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);//从缓存中取出
            //放入购物车的价格
            cartInfo.setCartPrice(skuInfo.getPrice());
            cartInfo.setSkuNum(skuNum);
            cartInfo.setImgUrl(skuInfo.getSkuDefaultImg());
            cartInfo.setSkuName(skuInfo.getSkuName());
            cartInfo.setIsChecked(1);
            //实时价格回显
            BigDecimal price = productFeignClient.getPrice(skuId);
            cartInfo.setSkuPrice(price);
            //DB 更新
//            cartInfoMapper.insert(cartInfo);
            //TODO 异步添加可能导致没有主键ID
            cartInfoAsyncService.insertAsync(cartInfo);
            System.out.println("addTOCart:" + Thread.currentThread().getName());
        }
        redisTemplate.opsForHash().put(cacheKey,skuId.toString(),cartInfo);
    }

    //添加购物车成功页面
    @Override
    public CartInfo toCart(Long skuId) {
        //获取userId无敌版，麻烦
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }

        System.out.println("userId = " + userId);
        String cacheKey = RedisConst.USER_KEY_PREFIX +
                userId + RedisConst.USER_CART_KEY_SUFFIX;
        CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cacheKey,skuId.toString());
        return cartInfo;
    }

    //查询购物车集合
    @Override
    public List<CartInfo> cartList(String userId, String userTempId) {
        //1、判断当前用户是否登录
        if (!StringUtils.isEmpty(userId)){
            //登录了
            if (!StringUtils.isEmpty(userTempId)){
                //有临时用户ID 大合并
                return mergeCartList(userId,userTempId);
            }else {
                //无临时用户 直接查询用户购物车
                return getCartListByUserId(userId);
            }
        }else {
            //未登录
            if (!StringUtils.isEmpty(userTempId)){
                //有临时用户ID 查询临时用户的购物车集合
                return getCartListByUserId(userTempId);
            }
        }
        //没有临时用户ID 直接返回NULL
        return null;
    }

    //选中或取消购物车
    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        String cacheKey = RedisConst.USER_KEY_PREFIX +
                userId + RedisConst.USER_CART_KEY_SUFFIX;
        //更新缓存
        CartInfo cartInfo  = (CartInfo) redisTemplate.opsForHash().
                get(cacheKey, skuId.toString());
        if (null != cartInfo){
            cartInfo.setIsChecked(isChecked);
            redisTemplate.opsForHash().put(cacheKey,skuId.toString(),cartInfo);
            //更新DB
            cartInfoMapper.update(cartInfo,new QueryWrapper<CartInfo>()
                    .eq("user_id",userId).eq("sku_id",skuId));
        }
    }

    //商品清单 购物车中选中的商品集合（结算页面查询
    @Override
    public List<CartInfo> checkedCartInfoList(String userId) {
        String cacheKey = RedisConst.USER_KEY_PREFIX +
                userId + RedisConst.USER_CART_KEY_SUFFIX;
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cacheKey);
        return cartInfoList.stream().filter(cartInfo -> (cartInfo.getIsChecked() == 1))
                .collect(Collectors.toList());
    }

    //合并真实用户与临时用户购物车集合
    private List<CartInfo> mergeCartList(String userId, String userTempId) {

        List<CartInfo> cartListByUserId = getCartListByUserId(userId);
        List<CartInfo> cartListByUserTempId = getCartListByUserId(userTempId);

        String cacheKeyByUserId = RedisConst.USER_KEY_PREFIX +
                userId + RedisConst.USER_CART_KEY_SUFFIX;
        String cacheKeyByUserTempId = RedisConst.USER_KEY_PREFIX +
                userTempId + RedisConst.USER_CART_KEY_SUFFIX;

        if (!CollectionUtils.isEmpty(cartListByUserId)){
            //真实用户有购物车集合
            if (!CollectionUtils.isEmpty(cartListByUserTempId)){
                //临时用户有购物车集合==>大合并！！--------------------------
                Map<Long, CartInfo> cartInfoMapByUserId = cartListByUserId.stream().collect
                        (Collectors.toMap(CartInfo::getSkuId, cartInfo -> cartInfo));
                //大合并开始
                cartListByUserTempId.forEach(cartInfoByUserTempId ->{
                    CartInfo cartInfoByUserId = cartInfoMapByUserId.get(
                            cartInfoByUserTempId.getSkuId());
                    if (null != cartInfoByUserId){
                        //1、出现相同的商品 数量之和
                        cartInfoByUserId.setSkuNum(
                                cartInfoByUserId.getSkuNum() + cartInfoByUserTempId.getSkuNum());
                        cartInfoByUserId.setIsChecked(1);
                        //更新DB  真实用户购物车数量  删掉临时用户购物车
                        cartInfoMapper.updateById(cartInfoByUserId);
                        cartInfoMapper.deleteById(cartInfoByUserTempId.getId());
                        //更新Redis
                        redisTemplate.opsForHash().put(cacheKeyByUserId,
                                cartInfoByUserId.getSkuId().toString(),cartInfoByUserId);
                        redisTemplate.opsForHash().delete(cacheKeyByUserTempId,
                                cartInfoByUserTempId.getSkuId().toString());
                    }else {
                        //出现不同的商品 直接添加
                        cartInfoMapByUserId.put(cartInfoByUserTempId.getSkuId(),
                                cartInfoByUserTempId);
                        //更新DB&&Redis  修改用户ID
                        cartInfoByUserTempId.setUserId(userId);
                        cartInfoMapper.updateById(cartInfoByUserTempId);

                        redisTemplate.opsForHash().put(cacheKeyByUserId,
                                cartInfoByUserTempId.getSkuId().toString(),cartInfoByUserTempId);
                        redisTemplate.opsForHash().delete(cacheKeyByUserTempId,
                                cartInfoByUserTempId.getSkuId().toString());
                    }
                });
                //返回 合并后的商品集合
                return new ArrayList<>(cartInfoMapByUserId.values());
            }else {
                //临时用户无购物车集合 直接返回真实用户购物车
                return cartListByUserId;
            }
        }else {
            //真实用户无购物车集合，直接返回临时用户购物车集合
            return cartListByUserTempId;
        }
    }

    //根据用户ID获取购物车集合
    private List<CartInfo> getCartListByUserId(String userId) {
        String cacheKey = RedisConst.USER_KEY_PREFIX +
                userId + RedisConst.USER_CART_KEY_SUFFIX;
        //map h -->  h.values();
        Date date = new Date();
        date.getTime();
        //排序
        List<CartInfo> values = redisTemplate.opsForHash().values(cacheKey);
        values.stream().sorted((cartInfo1,cartInfo2) -> {
            return (int) (cartInfo1.getSkuId() - cartInfo2.getSkuId());
        }).collect(Collectors.toList());

        return values;
    }
}
